package com.gla.service.impl;

import com.gla.common.ResponseCode;
import com.gla.dao.AddressMapper;
import com.gla.domain.*;
import com.gla.result.Result;
import com.gla.service.IAddressService;
import com.gla.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class AddressServiceimpl implements IAddressService {
    @Autowired
    AddressMapper addressMapper;

    //添加收货地址
    @Override
    public ServerResponse add(Address address,Integer user_id){
        if(address == null){
            return ServerResponse.createServerResponseByFail(ResponseCode.PARAMTER_NOT_EMPTY.getCode(),ResponseCode.PARAMTER_NOT_EMPTY.getMsg());
        }
        if(address.getIs_default() == 1){
            List<Address> address1 = addressMapper.selectAddressById(user_id);
            for (int i =0;i<address1.size();i++)
            {
                address1.get(i).setIs_default(0);
                updateAddress(address1.get(i));
            }
        }
        address.setUser_id(user_id);
        int count = addressMapper.insert(address);
        if(count == 0){//添加失败
            return ServerResponse.createServerResponseByFail(ResponseCode.ADDRESS_ADD_FAIL.getCode(),ResponseCode.ADDRESS_ADD_FAIL.getMsg());
        }


        return ServerResponse.createServerResponseBySuccess(address);
    }

    //查询所有收货地址
    public List<Address> getAddress(){
        return addressMapper.getAddress();
    }

    //根据id查询收货地址
    public List<Address> selectAddressById(int user_id){
        return addressMapper.selectAddressById(user_id);
    }

    //修改收货地址
    @Override
    public ServerResponse updateAddress(Address address) {
        if(address.getIs_default() == 1){
            List<Address> address2 = addressMapper.selectAddressById(address.getUser_id());
            for (int i =0;i<address2.size();i++)
            {
                address2.get(i).setIs_default(0);
                updateAddress(address2.get(i));
            }
        }
        int count = addressMapper.updateAddress(address);
        if(count == 0){
            //修改失败
            return ServerResponse.createServerResponseByFail(ResponseCode.ADDRESS_UPDATE_FAIL.getCode(),ResponseCode.ADDRESS_UPDATE_FAIL.getMsg());
        }
        //根据id查询
        Address address1 = addressMapper.selectByPrimaryKey(address.getId());
        return ServerResponse.createServerResponseBySuccess(address1);
    }

    //删除收货地址
    public void deleteAddressById(Integer id){
        addressMapper.deleteAddressById(id);
    }

    //根据id查询默认收货地址
    public List<Address> selectDefaultAddById(int user_id){
        return addressMapper.selectDefaultAddById(user_id);
    }
}
